<?php
/*
 +----------------------------------------------------------------------
 | TEMMOKUMVC [ NO BEST, ONLY BETTER ]
 +----------------------------------------------------------------------
 | Copyright (c) 2018~2019 https://www.temmoku.cn All rights reserved.
 +----------------------------------------------------------------------
 | Author: 张宗强 Email:webmaster@temmoku.cn QQ:158726877 516669373 TEL:17895221001 微信:temmokumvc
 +---------------------------------------------------------------------- 
*/
namespace admin\controller;
use \temmoku\db;
use \temmoku\admin;
use admin\public_class\cache;
class modular extends admin
{
	public function index(){
		$modular = db::select('*')->from(jab.'modular')->query();

		$arr=array_merge(C('MODULE_ROTUE'),C('Disable_modules'));
		if ( $handle  =  opendir ( APP_PATH )) {

			while (( $file  =  readdir ( $handle ))!== false) {
				
			 	if($file==='.' || $file==='..' || is_file(APP_PATH.$file) || in_array(strtolower($file),$arr)){
				    continue;
				}
				$r['modular']=include_once APP_PATH.$file.'/install.php';
				//+++要替换成下划线
				$file=str_replace("_","+++",$file);
				$r['dir']=$file;
			    $install[]=$r ;
			}
			//关闭打开的目录
			closedir ( $handle );
		}
		$this->assign('install', $install);
    	$this->assign('modular', $modular);
		$this->display(tpl('modular/index'));
	}
	public function edit(){
		$id=intval($_POST['id']);
		$data=db::select('*')->from(jab.'modular')->where('id='.$id)->row();
		hook_listen('modular_edit_begin',['data'=>$data]);
		if($id){
			if('name'===$_POST['step']){
				db::update(jab.'modular')->cols(array('name'=>$_POST['value']))->where('id='.$id)->query();
				db::update(jab.$data['table'].'setting')->cols(array('s_name'=>$_POST['value']))->where("s_key LIKE 'name'")->query();
			}elseif('domain'===$_POST['step']){
				$parse_url=parse_url ( $_POST['value']);
				$parse_url['host'] ? $_POST['value']=$parse_url['host'] : $_POST['value']=$parse_url['path'];
				$_POST['value']=trim(trim($_POST['value'],'/'));
				db::update(jab.'modular')->cols(array('domain'=>$_POST['value']))->where('id='.$id)->query();
				db::update(jab.$data['table'].'setting')->cols(array('s_name'=>$_POST['value']))->where("s_key LIKE 'domain'")->query();
			}
			define('M_MODULE',$data['dir']);
	        define('M_CONTROLLER','setting');
	        define('M_METHOD','cache');
			$modular_file= APP_PATH.$data['dir']."/public_class/cache.php";
    		if(is_file($modular_file)){
    			//加载此文件。
    			include_once $modular_file;
    			//执行相关操作
    			$controller=$data['dir']."\\public_class\\cache";
    			$controller::run($data);
    		}
		}
		cache::Make_Module_Route();
		hook_listen('modular_edit_end',['data'=>$data]);
		echo json_encode(['code'=>'0','text'=>'操作成功','value'=>$_POST['value']]);
	}
	
	public function install(){
		$data=include_once APP_PATH.$_GET['dir'].'/install.php';
		
		$arr=array_merge(C('MODULE_ROTUE'),C('Disable_modules'));
		
		if(in_array($_GET['dir'],$arr)){
			$this->err('已经安装过了,系统禁止再次安装');
		}
		
		if('post'===$_POST['step']){
			hook_listen('modular_install_begin');
			$test=db::select('*')->from(jab.'modular')->where("`table` LIKE '$_POST[table]'")->row();
			if($test){
				$this->err('已经存在数据表前戳，请重新输入');
			}
			$sql_dir=APP_PATH.$_GET['dir'].'/data.sql';
			if(is_file($sql_dir)){
				$sql=fils_content($sql_dir);
			}
			$sql=str_replace("temmoku_".$data['table'],jab.$_POST['table'],$sql);
			
			$explode=sql_regular_replace($sql);
			foreach($explode AS $V){
				if(!$_POST['Import']){//不倒入数据
					$is=stristr($V,'INSERT INTO');
					if($is){
						continue;
					}
				}
				db::query(trim($V));
			}


			//将要安装的模块信息插入模块库 star
			$post_data=[
				'name'=>$_POST['name'],
				'table'=>$_POST['table'],
				'dir'=>$_POST['dir'],
				'state'=>1,
				'initial_name'=>$data['initial_name'],
				'version'=>$data['version'],
				'update'=>$data['update']
			];
			$id = db::insert(jab.'modular')->cols($post_data)->query();
			//将要安装的模块信息插入模块库 end
			//需要将函数库的一些函数名进行替换，防止冲突 star
			$function_flie=APP_PATH.$_GET['dir'].'/function.php';
			if(is_file($function_flie)){
				$fils_content=fils_content($function_flie);
				$fils_content=preg_replace( '/\\\\/' , "\\\\\\"  , $fils_content );
				$fils_content=preg_replace('/function[\s]'.$data['initial_name'].'_/','function '.$_POST['dir']."_",$fils_content);
				write_file($function_flie,$fils_content);
			}
			//end
			if(!$_POST['Import']){//不倒入数据
				//插入setting必要数据
				db::insert(jab.$_POST['table'].'setting')->cols(array('s_key'=>'webstate','s_name'=>1))->query();
				db::insert(jab.$_POST['table'].'setting')->cols(array('s_key'=>'name','s_name'=>$_POST['name']))->query();
				db::insert(jab.$_POST['table'].'setting')->cols(array('s_key'=>'dir','s_name'=>$_POST['dir']))->query();
				db::insert(jab.$_POST['table'].'setting')->cols(array('s_key'=>'domain','s_name'=>''))->query();
			}else{
				db::update(jab.$_POST['table'].'setting')->cols(array('s_name'=>$_POST['name']))->where("s_key LIKE 'name'")->query();
				db::update(jab.$_POST['table'].'setting')->cols(array('s_name'=>$_POST['dir']))->where("s_key LIKE 'dir'")->query();
				db::update(jab.$_POST['table'].'setting')->cols(array('s_name'=>''))->where("s_key LIKE 'domain'")->query();
			}
			$install_path=APP_PATH.$_POST['dir'];
			
			//自动转移公共静态文件
			$public_dir=$install_path."/public/";
	    	if(is_dir($public_dir)){
				recurse_copy($public_dir,Temmoku_PATH."public/");
				delete_dir($public_dir);
			}
			
			//自动安装狗子
			$hook_dir=$install_path."/hook/";
			if(is_dir($hook_dir)){
				recurse_copy($hook_dir,APP_PATH."hook",'hook');
				delete_dir($hook_dir);
			}
			
			
			//将命名空间进行替换
		    recurse_replace($data['initial_name'],$_POST['dir'],$install_path);
			//移动模板目录
			move_tpl($install_path."/view/",$data['initial_name'],$_POST['dir']);
			
			$modular_file= $install_path."/public_class/cache.php";
			//卸载init.php文件
	    	@unlink($install_path."/init.php");
			cache::Make_Module_Route();
			cache::hook();
	    	if(is_file($modular_file)){
	    		//加载此文件。
	    		include_once $modular_file;
	    		//执行相关操作
	    		$controller=$_POST['dir']."\\public_class\\cache";
	    		$controller::run($post_data);
	    	}
			if(CACHING==true){
				define('CACHING_ALLCACHE',true);
				\temmoku\vendor\think\cache::rm('conf_file');
				\temmoku\vendor\think\cache::rm('_config');
			}
	    	hook_listen('modular_install_end',['dir'=>$_POST['dir']]);
			$this->success('模块安装成功','/admin/modular/index/');
		}
		$this->assign('data', $data);
		$this->display(tpl('modular/install'));
	}
	/*是否在前台会员中心显示*/
	public function user_show(){
		$id=intval($_POST['id']);
		db::update(jab.'modular')->cols(['user_show'=>$_POST['user_show']])->where('id='.$id)->query();
		cache::Make_Module_Route();
		echo json_encode(['code'=>'0','text'=>'操作成功']);
	}
	public function del(){
		if('install'===$_GET['step']){
			hook_listen('modular_del_begin',['dir'=>$_POST['dir']]);
			if(!$_GET['dir']){
				$this->err('缺少必要参数');
			}
			$_GET['dir']=strtolower(trim($_GET['dir'],'/\\'));
			
			$data=db::select('*')->from(jab.'modular')->where("dir LIKE '$_GET[dir]'")->row();
			if($data){
				$this->err('已经安装的模块不允许使用本方法卸载');
			}
			$dir=realpath(APP_PATH.$_GET['dir']);
			
			$dirs=['admin','user','conf','hook','plugin','install'];
			
			if(strripos($dir,APP_PATH) ===false  || is_file($dir)  || in_array($_GET['dir'],$dirs) || !is_dir($dir)){
				$this->err('要删除的目录不正确');
			}
			
			if(IS_WIN=='0' && function_exists('fileperms')){
				if(function_exists('chomd')){
					chomd($dir,'0777');
				}
				$fileperms= substr ( sprintf ( '%o' ,  fileperms ( $dir )), - 4 );
				if($fileperms < '0755'){
					$this->err('权限不足，无法删除,可以手动删除，或者把文件夹权限设置>=0755');
				}
			}
			
			//删除模块模板
			del_tpl($_GET['dir']);
			//删除模块文件
			delete_dir($dir);
			hook_listen('modular_del_end',['dir'=>$_POST['dir']]);
			$this->Success('模块删除成功');
		}else{
			$data=db::select('*')->from(jab.'modular')->where('id='.$_GET['id'])->row();
			if(!$data){
				$this->err('不存在的模块');
			}
			hook_listen('modular_uninstall_begin',['data'=>$data]);
			//获取所有表
			$table=db::query("SHOW TABLE STATUS");
			foreach($table as $row){
				//进行正则匹配。不能胡乱删除
				$regular='/'.jab.$data['table'].'/';
				preg_match_all($regular, $row['Name'], $matches);
				if($matches){
					if($matches[0]){
						$sql="DROP TABLE ".$row['Name'];
						db::query($sql);
					}
				}
			}
			//删除模块的信息
			db::delete(jab.'modular')->where('id='.$_GET['id'])->query();
			cache::Make_Module_Route($data['dir']);
			if(CACHING==true){
				define('CACHING_ALLCACHE',true);
				\temmoku\vendor\think\cache::rm('conf_file');
				\temmoku\vendor\think\cache::rm('_config');
			}
			hook_listen('modular_uninstall_end',['data'=>$data]);
			$this->Success('模块卸载成功');
		}
		
		$this->Success('模块删除成功');
	}
	public function copy(){
		if('post'===$_POST['step']){
			hook_listen('modular_copy_begin');
			$_POST['dir']=strtolower($_POST['dir']);
			if($_POST['dir']==='new'){
				$this->err('不允许的目录，如果非要此目录，请进行二次开发');
			}
			if(!$_POST['dir']){
				$this->err('必须输入文件夹名称');
			}
			if(!$_POST['jab']){
				$this->err('必须输入数据表前戳');
			}
			if(!$_POST['name']){
				$this->err('必须输入模块名称');
			}
			if(!preg_match ("/^[a-z]/i", $_POST['dir'])){
				 $this->err('文件夹名称必须是字母开头');
			}
			//新的位置
			$new_path=APP_PATH.$_POST['dir'];
			if(is_dir($new_path)){
				$this->err('文件夹已经存在，请重新输入');
			}
			$test=db::select('*')->from(jab.'modular')->where("`table` LIKE '$_POST[jab]'")->row();

			if($test){
				$this->err('已经存在数据表前戳，请重新输入');
			}
			$data=db::select('*')->from(jab.'modular')->where('id='.$_POST['id'])->row();
			if($data){
				
				//老位置
				$old_path=APP_PATH.$data['dir'];
				//复制文件
				recurse_copy($old_path,$new_path);
				//需要将函数库的一些函数名进行替换，防止冲突
				$function_flie=$new_path.'/function.php';
				if(is_file($function_flie)){
					$fils_content=fils_content($function_flie);
					$fils_content=preg_replace( '/\\\\/' , "\\\\\\"  , $fils_content );
					$fils_content=preg_replace('/function[\s]'.$data['dir'].'_/','function '.$_POST['dir']."_",$fils_content);
					write_file($function_flie,$fils_content);
				}
				//将要复制的模块信息插入模块库
				$post_data=[
					'name'=>$_POST['name'],
					'table'=>$_POST['jab'],
					'dir'=>$_POST['dir'],
					'state'=>1,
					'initial_name'=>$data['initial_name'],
					'version'=>$data['version']
				];
				$insert_id = db::insert(jab.'modular')->cols($post_data)->query();
				//获取所有表
				$table=db::query("SHOW TABLE STATUS");
				foreach($table as $row){
					$regular='/'.jab.strtolower($data['table']).'/';
					preg_match_all($regular, $row['Name'], $matches);
					if($matches){
						if($matches[0]){
							$_search  =jab.strtolower($data['table']);
							$_replace =jab.$_POST['jab'];
							$old_table=$row['Name'];
							$new_table = str_replace($_search,$_replace,$row['Name']);
							//不复制表内容，需要将创建的自定义模型剔除
							$Delete=[];
							if('-1'===$_POST['is_table_content']){
								//正则匹配老表的模型表,然后进行剔除
								$regular='/'.jab.$data['table'].'content_[0-9]+/';
								preg_match_all($regular, $row['Name'], $_matches);
								foreach($_matches as $t){
									if(!empty($t)){
										$Delete=$t;
									}
								}
							}
							if(!in_array($old_table,$Delete)){
								$sql="CREATE TABLE $new_table LIKE $old_table ";
								db::query($sql);
							}
							//复制表的内容
							if('1'===$_POST['is_table_content']){
								$sql1="INSERT INTO $new_table SELECT * FROM $old_table ";
								db::query($sql1);
							}
						}
					}
				}
				//进行新模块的一些信息更新.如果是复制的话
				if('1'===$_POST['is_table_content']){
					//更新
					db::update(jab.$_POST['jab'].'setting')->cols(array('s_name'=>$_POST['name']))->where("s_key LIKE 'name'")->query();
					db::update(jab.$_POST['jab'].'setting')->cols(array('s_name'=>strtolower($_POST['jab'])))->where("s_key LIKE 'm_jab'")->query();
					db::update(jab.$_POST['jab'].'setting')->cols(array('s_name'=>$_POST['dir']))->where("s_key LIKE 'dir'")->query();
					db::update(jab.$_POST['jab'].'setting')->cols(array('s_name'=>''))->where("s_key LIKE 'domain'")->query();
				}else{
					//插入
					db::insert(jab.$_POST['jab'].'setting')->cols(array('s_key'=>'webstate','s_name'=>1))->query();
					db::insert(jab.$_POST['jab'].'setting')->cols(array('s_key'=>'name','s_name'=>$_POST['name']))->query();
					db::insert(jab.$_POST['jab'].'setting')->cols(array('s_key'=>'m_jab','s_name'=>strtolower($_POST['jab'])))->query();
					db::insert(jab.$_POST['jab'].'setting')->cols(array('s_key'=>'dir','s_name'=>$_POST['dir']))->query();
					db::insert(jab.$_POST['jab'].'setting')->cols(array('s_key'=>'domain','s_name'=>$_POST['domain']))->query();
				}
		       	//将命名空间进行替换
		       	recurse_replace($data['dir'],$_POST['dir'],$new_path);
				$modular_file= APP_PATH.$_POST['dir']."/public_class/cache.php";
				
				//卸载init.php文件
	    		@unlink(APP_PATH.$_POST['dir']."/init.php");
	    		cache::Make_Module_Route();
				
	    		if(is_file($modular_file)){
	    			//加载此文件。
	    			include_once $modular_file;
	    			//执行相关操作
	    			$controller=$_POST['dir']."\public_class\cache";
	    			$controller::run($post_data);
	    		}
				//复制模板
				copy_tpl($data['dir'],$_POST['dir']);
	    		hook_listen('modular_copy_end');
				$this->Success('复制成功','/admin/modular/index');
			}else{
				$this->err('不存在的模块');
			}
		}
		$data=db::select('*')->from(jab.'modular')->where('id='.$_GET['id'])->row();
		$this->assign('data', $data);
		$this->assign('id', $_GET['id']);
		$this->display(tpl('modular/copy'));
	}
	
	
	public function state(){
		$state=intval($_POST['state']);
		$id=intval($_POST['id']);
		$data=db::select('*')->from(jab.'modular')->where('id='.$id)->row();
		if($id){
			db::update(jab.'modular')->cols(array('state'=>$state))->where('id='.$id)->query();
			db::update(jab.$data['table'].'setting')->cols(array('s_name'=>$state))->where("s_key LIKE 'webstate'")->query();
			$file=APP_PATH.$data['dir']."/public_class/cache.php";
			if(is_file($file)){
				include $file;
				$class="$data[dir]\\public_class\\cache";
				$class::run($data);
			}
		}
		cache::Make_Module_Route();
		echo json_encode(['code'=>'0','text'=>'操作成功']);
	}
	

	
}
?>
